package com.xge.component_caipu.binder

import androidx.core.view.isGone
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.xge.common_libary.bean.CaiPuListInfoSection
import com.xge.common_libary.bean.CollectCpEntity
import com.xge.common_libary.view.utils.BaseBindingBinder
import com.xge.common_libary.view.utils.BindingViewHolder
import om.xge.component_caipu.R
import om.xge.component_caipu.databinding.ItemCollectContentBinding

abstract class ItemCollectContentBinder(
    private val isCheckHide: () -> Boolean, private var checks: ArrayList<String>
) : BaseBindingBinder<CollectCpEntity, ItemCollectContentBinding>(ItemCollectContentBinding::inflate) {

    override fun onViewHolderCreated(holder: BindingViewHolder<CollectCpEntity, ItemCollectContentBinding>) {
        super.onViewHolderCreated(holder)
        holder.itemView.setOnClickListener {
            holder.item?.let {
                onItemClick(it)
            }
        }
    }

    override fun onBindViewHolder(
        holder: BindingViewHolder<CollectCpEntity, ItemCollectContentBinding>, item: CollectCpEntity
    ) {
        holder.run {
            val section = Gson().fromJson(item.content, CaiPuListInfoSection::class.java)
            binding.tvTitle.text = section.name
            Glide.with(holder.context).load(section.pic).into(binding.ivCover)
            binding.tvTag.text = section.tag

            binding.ivBox.isGone = this@ItemCollectContentBinder.isCheckHide()

            // 正确使用 item.sid 判断是否选中
            if (checks.contains(item.sid)) {
                binding.ivBox.tag = "checked"
                binding.ivBox.setImageResource(R.mipmap.ic_checkd)
            } else {
                binding.ivBox.tag = "unchecked"
                binding.ivBox.setImageResource(R.mipmap.ic_uncheck)
            }

            binding.ivBox.setOnClickListener {
                val tag = binding.ivBox.tag
                if (tag == "checked") {
                    binding.ivBox.setImageResource(R.mipmap.ic_uncheck)
                    binding.ivBox.tag = "unchecked"
                    checks.remove(item.sid)
                } else {
                    binding.ivBox.setImageResource(R.mipmap.ic_checkd)
                    binding.ivBox.tag = "checked"
                    if (!checks.contains(item.sid)) {
                        checks.add(item.sid)
                    }
                }
            }
        }
    }
    abstract fun onItemClick(item:CollectCpEntity)
}
